// web/src/composables/useChatStream.ts

import { ref, computed } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { useChatStore } from '@/stores/chatStore';
import type { StreamEvent, ChatMessage } from '@/types/chat';

/**
 * SSE 聊天流处理组合式函数
 * 负责处理消息发送、流式响应、错误处理和状态管理
 */
export function useChatStream() {
  const authStore = useAuthStore();
  const chatStore = useChatStore();
  
  // 响应式状态
  const isStreaming = ref(false);
  const streamError = ref<string | null>(null);
  const currentStreamController = ref<AbortController | null>(null);
  const reconnectAttempts = ref(0);
  const maxReconnectAttempts = 3;

  // 计算属性
  const canSendMessage = computed(() => {
    return !isStreaming.value && !chatStore.isSending && chatStore.currentConversationId;
  });

  /**
   * 发送消息并处理流式响应
   */
  const sendMessage = async (content: string): Promise<boolean> => {
    if (!content.trim() || !canSendMessage.value) {
      return false;
    }

    // 重置状态
    streamError.value = null;
    isStreaming.value = true;
    reconnectAttempts.value = 0;

    // 创建中止控制器
    currentStreamController.value = new AbortController();

    try {
      await processStream(content, currentStreamController.value.signal);
      return true;
    } catch (error) {
      console.error('Send message failed:', error);
      streamError.value = error instanceof Error ? error.message : '发送消息失败';
      return false;
    } finally {
      isStreaming.value = false;
      currentStreamController.value = null;
    }
  };

  /**
   * 处理 SSE 流
   */
  const processStream = async (content: string, signal: AbortSignal): Promise<void> => {
    const conversationId = chatStore.currentConversationId;
    if (!conversationId) {
      throw new Error('没有活跃的对话');
    }

    // 乐观更新：先添加用户消息
    const userMessage: ChatMessage = {
      id: `temp-${Date.now()}`,
      conversation_id: conversationId,
      role: 'user',
      content: content.trim(),
      created_at: new Date().toISOString()
    };
    chatStore.addMessage(userMessage);

    // 添加 AI 消息占位符
    const aiMessageId = `temp-ai-${Date.now()}`;
    const aiMessage: ChatMessage = {
      id: aiMessageId,
      conversation_id: conversationId,
      role: 'assistant',
      content: '',
      steps: [],
      created_at: new Date().toISOString()
    };
    chatStore.addMessage(aiMessage);

    const response = await fetch(`/api/v1/conversations/${conversationId}/messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authStore.token}`
      },
      body: JSON.stringify({ content: content.trim() }),
      signal
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    if (!response.body) {
      throw new Error('ReadableStream not supported');
    }

    await readStream(response.body, aiMessage);
  };

  /**
   * 读取和处理 SSE 流
   */
  const readStream = async (body: ReadableStream<Uint8Array>, aiMessage: ChatMessage): Promise<void> => {
    const reader = body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    try {
      while (true) {
        const { done, value } = await reader.read();
        
        if (done) {
          // 流正常结束
          handleStreamComplete(aiMessage);
          break;
        }

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const dataStr = line.substring(6).trim();
            
            if (dataStr === '[DONE]') {
              handleStreamComplete(aiMessage);
              return;
            }

            try {
              const event: StreamEvent = JSON.parse(dataStr);
              handleStreamEvent(aiMessage, event);
            } catch (parseError) {
              console.warn('SSE JSON parse error:', parseError, 'Data:', dataStr);
            }
          }
        }
      }
    } catch (error) {
      if (error instanceof Error && error.name === 'AbortError') {
        console.log('Stream aborted by user');
      } else {
        console.error('Stream reading error:', error);
        streamError.value = '流读取中断，请重试';
        handleStreamError(aiMessage, error);
      }
    } finally {
      reader.releaseLock();
    }
  };

  /**
   * 处理单个流事件
   */
  const handleStreamEvent = (aiMessage: ChatMessage, event: StreamEvent) => {
    if (!aiMessage.steps) {
      aiMessage.steps = [];
    }

    const stepIndex = aiMessage.steps.findIndex(s => s.step === event.step);

    switch (event.type) {
      case 'thought':
        if (stepIndex === -1) {
          aiMessage.steps.push({
            step: event.step!,
            type: 'thought',
            content: event.content || ''
          });
        } else {
          // 追加思考内容（支持增量更新）
          const existingContent = aiMessage.steps[stepIndex].content || '';
          aiMessage.steps[stepIndex].content = existingContent + (event.content || '');
        }
        break;

      case 'tool_call':
        if (stepIndex === -1) {
          aiMessage.steps.push({
            step: event.step!,
            type: 'tool_call',
            tool_name: event.tool_name || 'unknown',
            arguments: event.arguments || {},
            status: 'running'
          });
        } else {
          Object.assign(aiMessage.steps[stepIndex], {
            type: 'tool_call',
            tool_name: event.tool_name,
            arguments: event.arguments,
            status: 'running'
          });
        }
        break;

      case 'tool_result':
        if (stepIndex === -1) {
          aiMessage.steps.push({
            step: event.step!,
            type: 'tool_result',
            tool_name: event.tool_name || 'unknown',
            result: event.result || '',
            status: event.status as any || 'completed',
            images: event.images || []
          });
        } else {
          Object.assign(aiMessage.steps[stepIndex], {
            type: 'tool_result',
            result: event.result,
            status: event.status,
            images: event.images || aiMessage.steps[stepIndex].images || []
          });
        }
        break;

      case 'finish':
        if (event.content) {
          aiMessage.content = event.content;
        }
        break;

      case 'error':
        console.error('Stream error event:', event.content);
        streamError.value = event.content || '流处理发生错误';
        break;
    }

    // 触发 UI 更新
    chatStore.updateMessage(aiMessage.id, { ...aiMessage });
  };

  /**
   * 处理流完成
   */
  const handleStreamComplete = (_aiMessage: ChatMessage) => {
    console.log('Stream completed successfully');
    // 可以在这里添加完成后的清理逻辑
  };

  /**
   * 处理流错误
   */
  const handleStreamError = (aiMessage: ChatMessage, error: any) => {
    console.error('Stream processing error:', error);
    
    // 更新 AI 消息显示错误
    aiMessage.content = '消息处理中断，请重试。';
    if (error instanceof Error) {
      aiMessage.content += `\n错误: ${error.message}`;
    }
    
    chatStore.updateMessage(aiMessage.id, { ...aiMessage });
  };

  /**
   * 中止当前流
   */
  const abortStream = () => {
    if (currentStreamController.value) {
      currentStreamController.value.abort();
      currentStreamController.value = null;
      isStreaming.value = false;
    }
  };

  /**
   * 重试发送消息
   */
  const retrySendMessage = async (content: string): Promise<boolean> => {
    if (reconnectAttempts.value >= maxReconnectAttempts) {
      streamError.value = '重试次数过多，请检查网络连接';
      return false;
    }

    reconnectAttempts.value++;
    console.log(`Retry attempt ${reconnectAttempts.value}...`);
    
    return await sendMessage(content);
  };

  /**
   * 清除错误状态
   */
  const clearError = () => {
    streamError.value = null;
    reconnectAttempts.value = 0;
  };

  /**
   * 自动清理：组件卸载时中止流
   */
  const cleanup = () => {
    abortStream();
  };

  return {
    // 状态
    isStreaming: computed(() => isStreaming.value),
    streamError: computed(() => streamError.value),
    canSendMessage,

    // 方法
    sendMessage,
    abortStream,
    retrySendMessage,
    clearError,
    cleanup
  };
}
